package cc.md888.result;



import java.io.Serializable;
import java.util.function.Function;


/**
 * 标准的 Restful 请求响应实体。
 */
public class Result<T> implements Serializable {

    /**
     * 响应 Code
     */
    private String code;
    /**
     * 是否成功
     */
    private Boolean success;

    /**
     * 消息
     */
    private String message;

    /**
     * 响应数据
     */
    private T data;

    public Result() {
    }


    private Result(String code, String message, T data, boolean success) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.success = success;
    }


    public String getCode() {
        return code;
    }

    public Boolean getSuccess() {
        return success;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }


    public Result<T> code(String code) {
        this.code = code;
        return this;
    }

    public Result<T> message(String message) {
        this.message = message;
        return this;
    }

    public Result<T> data(T data) {
        this.data = data;
        return this;
    }

    public static  <T> Result<T> ok(){
        return new Result<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null, true);
    }


    public static  <T> Result<T> ok(T data){
        return new Result<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data, true);
    }


    public static  <T> Result<T> ok(T data, String mesg){
        return new Result<T>(ResultCode.SUCCESS.getCode(), mesg, data, true);
    }



    public static  <T> Result<T> error(){
        return new Result<>(ResultCode.ERROR.getCode(), null, null, false);
    }


    public static  <T> Result<T> error(String message){
        return new Result<>(ResultCode.ERROR.getCode(), message, null, false);
    }

    public static  <T> Result<T> error(String code, String message, T data){
        return new Result<>(code, message, data, false);
    }


    public static  <T> Result<T> error(String code, String message){
        return new Result<>(code, message, null, false);
    }


    public static <T, R> Result<R> map(Result<T> result, Function<T, R> convert){
        R data = convert.apply(result.data);
        return new Result<R>(result.code, result.message, data, result.success);
    }

    @Override
    public String toString() {
        return "Result{" +
                "code='" + code + '\'' +
                ", success=" + success +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
